import React, { useState, useEffect } from 'react';
import {
  Table, Card, Form, Input, Button, Space, DatePicker, Select,
  Tag, message, Tooltip, Modal, Typography, Divider, Row, Col
} from 'antd';
import {
  SearchOutlined, ReloadOutlined,
  EyeOutlined, CalendarOutlined, UserOutlined,
  GlobalOutlined, ClockCircleOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { useLocation } from 'react-router-dom';
import OperationNavBar from '../components/OperationNavBar';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { Text } = Typography;

// API基础URL
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

// 获取token
const getToken = () => {
  return localStorage.getItem('token') || '';
};

// 用户数据接口定义
interface UserData {
  uid: string;
  user: string;
}

// API响应接口定义
interface UserResponse {
  code: number;
  data: UserData[];
}

// 日志数据接口定义
interface LogRecord {
  lid: number;
  uid: number;
  module: string;
  operate: string;
  logs: string;
  ip: string;
  ctime: string;
  user: string;
}

// 查询参数接口定义
interface QueryParams {
  st: string;
  et: string;
  module: string;
  operate: string;
  user: string;
  key: string;
  page: number;
  ps: number;
}

// API响应接口定义
interface LogResponse {
  code: number;
  data: LogRecord[];
  total: number;
}

const LogManagement: React.FC = () => {
  const [form] = Form.useForm();
  const location = useLocation();
  const [loading, setLoading] = useState<boolean>(false);
  const [logData, setLogData] = useState<LogRecord[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [detailModalVisible, setDetailModalVisible] = useState<boolean>(false);
  const [selectedRecord, setSelectedRecord] = useState<LogRecord | null>(null);
  const [userList, setUserList] = useState<UserData[]>([]);
  const [loadingUsers, setLoadingUsers] = useState<boolean>(false);

  // 处理用户选择变化
  const handleUserChange = (value: string[]) => {
    form.setFieldValue('user', value || []);
  };

  // 操作类型选项
  const operateOptions = [
    { label: '全部', value: '' },
    { label: '新增', value: '新增' },
    { label: '修改', value: '修改' },
    { label: '删除', value: '删除' },
    { label: '查询', value: '查询' },
    { label: '导出', value: '导出' },
    { label: '登录', value: '登录' },
    { label: '登出', value: '登出' },
  ];

  // 模块类型选项
  const moduleOptions = [
    { label: '全部', value: '' },
    { label: '数据检索', value: '数据检索' },
    { label: '数据管理', value: '数据管理' },
    { label: '用户管理', value: '用户管理' },
    { label: '系统配置', value: '系统配置' },
    { label: '权限管理', value: '权限管理' },
  ];

  // 获取用户列表
  const fetchUserList = async () => {
    setLoadingUsers(true);
    const token = getToken();
    try {
      const response = await fetch(`${API_BASE_URL}/-/bin.sysLogs.get_logs_user`, {
        method: 'GET',
        headers: {
          'token': token
        }
      });

      if (!response.ok) {
        throw new Error(`API调用失败: ${response.statusText}`);
      }

      const result: UserResponse = await response.json();
      if (result && result.code === 200) {
        setUserList(result.data || []);
      } else {
        console.error('获取用户列表失败');
        setUserList([]);
      }
    } catch (error: any) {
      console.error('获取用户列表错误:', error);
      setUserList([]);
    } finally {
      setLoadingUsers(false);
    }
  };

  // API调用函数
  const callApi = async (params: QueryParams): Promise<LogResponse> => {
    const token = getToken();
    try {
      const response = await fetch(`${API_BASE_URL}/-/bin.sysLogs.get_sys_logs`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'token': token
        },
        body: JSON.stringify(params)
      });

      if (!response.ok) {
        throw new Error(`API调用失败: ${response.statusText}`);
      }

      const result = await response.json();
      return result;
    } catch (error: any) {
      console.error('API调用错误:', error);
      message.error(`API错误: ${error.message}`);
      throw error;
    }
  };

  // 加载日志数据
  const loadLogData = async (params?: Partial<QueryParams>) => {
    setLoading(true);
    try {
      const formValues = form.getFieldsValue();
      const queryParams: QueryParams = {
        st: params?.st || (formValues.timeRange?.[0] ? formValues.timeRange[0].startOf('day').format('YYYY-MM-DD HH:mm:ss') : ''),
        et: params?.et || (formValues.timeRange?.[1] ? formValues.timeRange[1].endOf('day').format('YYYY-MM-DD HH:mm:ss') : ''),
        module: params?.module || formValues.module || '',
        operate: params?.operate || formValues.operate || '',
        user: params?.user || (() => {
          const userValue = formValues.user;
          if (Array.isArray(userValue)) {
            return userValue.includes('') ? '' : userValue.join(',');
          }
          return userValue || '';
        })(),
        key: params?.key || formValues.keyword || '',
        page: params?.page || currentPage,
        ps: params?.ps || pageSize
      };

      const result = await callApi(queryParams);
      
      if (result && result.code === 200) {
        setLogData(result.data || []);
        setTotal(result.total || 0);
        // message.success(`成功加载 ${result.total || 0} 条日志记录`);
      } else {
        message.error('加载日志失败');
        setLogData([]);
        setTotal(0);
      }
    } catch (error) {
      console.error('加载日志数据失败:', error);
      setLogData([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  // 搜索处理
  const handleSearch = (values: any) => {
    setCurrentPage(1);
    loadLogData({ page: 1 });
  };

  // 重置搜索
  const handleReset = () => {
    form.resetFields();
    setCurrentPage(1);
    setLogData([]);
    setTotal(0);
  };

  // 页码变化处理
  const handleTableChange = (page: number, size: number) => {
    setCurrentPage(page);
    setPageSize(size);
    loadLogData({ page, ps: size });
  };

  // 查看详情
  const showDetail = (record: LogRecord) => {
    setSelectedRecord(record);
    setDetailModalVisible(true);
  };


  // 获取操作类型的颜色
  const getOperateColor = (operate: string): string => {
    const colorMap: { [key: string]: string } = {
      '新增': 'green',
      '修改': 'blue',
      '删除': 'red',
      '查询': 'cyan',
      '导出': 'orange',
      '登录': 'purple',
      '登出': 'default'
    };
    return colorMap[operate] || 'default';
  };

  // 表格列定义
  const columns: ColumnsType<LogRecord> = [
    {
      title: '日志ID',
      dataIndex: 'lid',
      key: 'lid',
      width: 80,
      sorter: (a, b) => a.lid - b.lid,
    },
    {
      title: '用户信息',
      key: 'userInfo',
      width: 150,
      render: (_, record) => (
        <Space direction="vertical" size={0}>
          <Text strong>{record.user}</Text>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            <UserOutlined /> ID: {record.uid}
          </Text>
        </Space>
      ),
    },
    {
      title: '模块',
      dataIndex: 'module',
      key: 'module',
      width: 120,
      filters: moduleOptions.slice(1).map(opt => ({ text: opt.label, value: opt.value })),
      onFilter: (value, record) => record.module === value,
    },
    {
      title: '操作类型',
      dataIndex: 'operate',
      key: 'operate',
      width: 100,
      render: (operate: string) => (
        <Tag color={getOperateColor(operate)}>{operate}</Tag>
      ),
      filters: operateOptions.slice(1).map(opt => ({ text: opt.label, value: opt.value })),
      onFilter: (value, record) => record.operate === value,
    },
    {
      title: '操作详情',
      dataIndex: 'logs',
      key: 'logs',
      ellipsis: {
        showTitle: false,
      },
      render: (logs: string) => (
        <Tooltip title={logs} placement="topLeft">
          <Text style={{ maxWidth: 200 }}>{logs}</Text>
        </Tooltip>
      ),
    },
    {
      title: 'IP地址',
      dataIndex: 'ip',
      key: 'ip',
      width: 120,
      render: (ip: string) => (
        <Space>
          <GlobalOutlined />
          <Text code>{ip}</Text>
        </Space>
      ),
    },
    {
      title: '操作时间',
      dataIndex: 'ctime',
      key: 'ctime',
      width: 160,
      sorter: (a, b) => dayjs(a.ctime).unix() - dayjs(b.ctime).unix(),
      render: (ctime: string) => (
        <Space direction="vertical" size={0}>
          <Text>{dayjs(ctime).format('YYYY-MM-DD')}</Text>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            <ClockCircleOutlined /> {dayjs(ctime).format('HH:mm:ss')}
          </Text>
        </Space>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 80,
      fixed: 'right',
      render: (_, record) => (
        <Button
          type="text"
          icon={<EyeOutlined />}
          onClick={() => showDetail(record)}
          size="small"
        >
          详情
        </Button>
      ),
    },
  ];

  // 初始化
  useEffect(() => {
    // 设置默认时间范围为最近7天
    const endTime = dayjs();
    const startTime = dayjs().subtract(7, 'days');
    
    // 解析URL参数
    const searchParams = new URLSearchParams(location.search);
    const moduleFromUrl = searchParams.get('module');
    
    form.setFieldsValue({
      timeRange: [startTime, endTime],
      module: moduleFromUrl || '',
      keyword: '失败'
    });
    
    // 加载用户列表
    fetchUserList();
    
    // 页面初始化时自动加载最近7天的数据
    setTimeout(() => {
      loadLogData({
        st: startTime.startOf('day').format('YYYY-MM-DD HH:mm:ss'),
        et: endTime.endOf('day').format('YYYY-MM-DD HH:mm:ss'),
        module: moduleFromUrl || '',
        operate: '',
        user: '',
        key: '失败',
        page: 1,
        ps: pageSize
      });
    }, 100);
  }, [form, location.search, pageSize]);

  return (
    <div className="log-management" style={{ background: '#f5f5f5', padding: '0 0 24px 0' }}>
      {/* 运行管理导航条 */}
      <OperationNavBar />
      
      <Card className="search-card" style={{ marginBottom: 16 }}>
        <Form
          form={form}
          onFinish={handleSearch}
          layout="vertical"
        >
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item 
                label="日期范围" 
                name="timeRange"
                rules={[{ required: true, message: '请选择日期范围' }]}
              >
                <RangePicker
                  format="YYYY-MM-DD"
                  placeholder={['开始日期', '结束日期']}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item label="模块" name="module">
                <Select
                  placeholder="选择模块"
                  allowClear
                  options={moduleOptions}
                />
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item label="操作类型" name="operate">
                <Input
                  placeholder="输入操作类型"
                  allowClear
                />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item 
                label="用户" 
                name="user"
                tooltip="选择用户或手动输入用户ID"
              >
                <Select
                  placeholder="选择用户(可多选)"
                  allowClear
                  showSearch
                  mode="multiple"
                  loading={loadingUsers}
                  optionFilterProp="label"
                  onChange={handleUserChange}
                  filterOption={(input, option) =>
                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                  }
                  options={userList.map(user => ({
                    label: user.user,
                    value: user.uid
                  }))}
                />
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item 
                label="关键词" 
                name="keyword"
                tooltip="搜索日志内容中的关键词"
              >
                <Input
                  placeholder="输入关键词"
                  allowClear
                />
              </Form.Item>
            </Col>
            <Col span={5}>
              <Form.Item label=" " style={{ marginBottom: 0 }}>
                <Space>
                  <Button
                    type="primary"
                    icon={<SearchOutlined />}
                    htmlType="submit"
                    loading={loading}
                  >
                    查询
                  </Button>
                  <Button
                    icon={<ReloadOutlined />}
                    onClick={handleReset}
                  >
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card 
        className="content-card"
        title={`系统日志管理 (共 ${total} 条记录)`}
        extra={
          <Button
            icon={<ReloadOutlined />}
            onClick={() => loadLogData()}
            loading={loading}
          >
            刷新
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={logData}
          rowKey="lid"
          loading={loading}
          pagination={{
            current: currentPage,
            pageSize: pageSize,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条 / 共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100'],
            onChange: handleTableChange,
            onShowSizeChange: handleTableChange,
          }}
          scroll={{ x: 'max-content' }}
          bordered
          size="middle"
        />
      </Card>

      {/* 详情模态框 */}
      <Modal
        title="日志详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={600}
      >
        {selectedRecord && (
          <div>
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <Text strong>日志ID：</Text>
                <Text>{selectedRecord.lid}</Text>
              </Col>
              <Col span={12}>
                <Text strong>用户ID：</Text>
                <Text>{selectedRecord.uid}</Text>
              </Col>
              <Col span={12}>
                <Text strong>用户名：</Text>
                <Text>{selectedRecord.user}</Text>
              </Col>
              <Col span={12}>
                <Text strong>IP地址：</Text>
                <Text code>{selectedRecord.ip}</Text>
              </Col>
              <Col span={12}>
                <Text strong>模块：</Text>
                <Text>{selectedRecord.module}</Text>
              </Col>
              <Col span={12}>
                <Text strong>操作类型：</Text>
                <Tag color={getOperateColor(selectedRecord.operate)}>
                  {selectedRecord.operate}
                </Tag>
              </Col>
              <Col span={24}>
                <Text strong>操作时间：</Text>
                <Text>{selectedRecord.ctime}</Text>
              </Col>
            </Row>
            <Divider />
            <div>
              <Text strong>操作详情：</Text>
              <div style={{ 
                marginTop: 8, 
                padding: 12, 
                background: '#f5f5f5', 
                borderRadius: 4,
                wordBreak: 'break-all'
              }}>
                {selectedRecord.logs}
              </div>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default LogManagement;